
import random
import re
from datetime import datetime

from flask import request, abort, current_app, make_response, jsonify, session

from info import redis_store, constants, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utlis.captcha.captcha import captcha
from info.utlis.response_code import RET
from . import passport_blue

@passport_blue.route("/logout")
def logout():
    session.pop("user_id", None)
    session.pop("mobile", None)
    session.pop("nick_name", None)
    session.pop("is_admin", None)
    return jsonify(errno=RET.OK, errmsg="退出成功")

@passport_blue.route("/login", methods=["POST"])
def login():
    """
        登录
        1. 获取参数
        2. 校验参数
        3. 校验密码是否正确
        4. 保存用户的登录状态
        5. 响应
        :return:
        """
    pramas = request.json
    print(pramas)
    mobile = pramas.get("mobile")
    passport = pramas.get("passport")
    print(mobile)
    print(passport)
    if not all([mobile, passport]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数输入有误")
    if not re.match(r"1[35678]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码格式错误")
    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    if not user.check_password(passport):
        return jsonify(errno=RET.PWDERR, errmsg="用户名或密码错误")

    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    user.last_login = datetime.now()
    # try:
    #     db.session.commit()
    # except Exception as e:
    #     db.session.rollback()
    #     current_app.logger.error(e)
    return jsonify(errno=RET.OK, errmsg="登录成功")



@passport_blue.route("/register", methods=["POST"])
def register():
    """
        注册的逻辑
        1. 获取参数
        2. 校验参数
        3. 取到服务器保存的真实的短信验证码内容
        4. 校验用户输入的短信验证码内容和真实验证码内容是否一致
        5. 如果一致，初始化 User 模型，并且赋值属性
        6. 将 user 模型添加数据库
        7. 返回响应
        :return:
        """
    pramas = request.json
    mobile = pramas.get("mobile")
    smscode = pramas.get("smscode")
    password = pramas.get("password")

    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不能有空")
    if not re.match(r"1[35678]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")
    try:
        real_sms_code = redis_store.get("SMS"+mobile)
        print(real_sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")
    if real_sms_code != smscode:
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.last_login = datetime.now()
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据存储失败")
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name

    return jsonify(errno=RET.OK, errmsg="注册成功")



@passport_blue.route("/smscode", methods=["POST"])
def send_sms():
    """
        1. 接收参数并判断是否有值
        2. 校验手机号是正确
        3. 通过传入的图片编码去redis中查询真实的图片验证码内容
        4. 进行验证码内容的比对
        5. 生成发送短信的内容并发送短信
        6. redis中保存短信验证码内容
        7. 返回发送成功的响应
        :return:
        """


    params_dict = request.json
    print(params_dict)
    mobile = params_dict.get("mobile")
    image_code = params_dict.get("image_code")
    image_code_id = params_dict.get("image_code_id")

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数有误")

    if not re.match(r"1[3578]\d{9}", mobile):
        return jsonify(errno = RET.PARAMERR, errmsg = "手机号格式不正确")

    try:
        real_img_code = redis_store.get("ImageCodeId"+image_code_id)
        print(real_img_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = "数据查询失败")

    if not real_img_code:
        return jsonify(errno = RET.NODATA, errmsg = "图片验证码过期")
    if real_img_code.upper() != image_code.upper():
        return jsonify(errno = RET.DATAERR, errmsg = "验证码错误")

    sms_code_str = "%06d" %random.randint(0,999999)
    current_app.logger.debug(sms_code_str)
    try:
        redis_store.set("SMS"+mobile,sms_code_str, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = "数据保存失败")
    result = CCP().send_template_sms(mobile, [sms_code_str, constants.SMS_CODE_REDIS_EXPIRES / 60],"1")

    if result != 0:
        return jsonify(errno = RET.THIRDERR, errmsg = "发送短信失败")

    return jsonify(errno = RET.OK, errmsg = "发送成功")



@passport_blue.route("/image_code")
def get_pass_code():
    image_code_id = request.args.get("imageCodeId")
    if not image_code_id:
        return abort(403)
    name, text, image = captcha.generate_captcha()

    try:
        redis_store.set("ImageCodeId"+image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response